#include "stm32f10x.h"                  // Device header
#include "Delay.h"

#define CSB_Trigger_Clcock				RCC_APB2Periph_GPIOB
#define CSB_Echo_Clcock						RCC_APB2Periph_GPIOA
#define CSB_Echo_Timer_Clock			RCC_APB2Periph_TIM1
#define CSB_Echo_Timer						TIM1
#define CSB_Trigger_Port					GPIOB
#define CSB_Trigger_Pin						GPIO_Pin_15
#define CSB_Echo_Port							GPIOA
#define CSB_Echo_Pin							GPIO_Pin_8

void CSB_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_ICInitTypeDef TIM_ICInitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;

	RCC_APB2PeriphClockCmd(CSB_Trigger_Clcock | CSB_Echo_Clcock | CSB_Echo_Timer_Clock, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = CSB_Trigger_Pin ;		//triger
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(CSB_Trigger_Port, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_InitStructure.GPIO_Pin = CSB_Echo_Pin;	//echo
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(CSB_Echo_Port, &GPIO_InitStructure);
	
	TIM_InternalClockConfig(CSB_Echo_Timer);
	
	// 配置定时器时基
	TIM_TimeBaseInitStructure.TIM_Period = 0xFFFF;                // 计数器最大值
	TIM_TimeBaseInitStructure.TIM_Prescaler = 72 - 1;             // 72MHz / 72 = 1MHz (1us)
	TIM_TimeBaseInitStructure.TIM_ClockDivision = 0;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;          // 高级定时器需要配置重复计数器
	TIM_TimeBaseInit(CSB_Echo_Timer, &TIM_TimeBaseInitStructure);
	
	// 配置定时器输入捕获（CH1）
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;        // 不分频，每次边沿都捕获
	TIM_ICInitStructure.TIM_ICFilter = 0x0;                       // 不滤波
	TIM_ICInit(CSB_Echo_Timer, &TIM_ICInitStructure);

	// 使能TIM1捕获中断
	TIM_ITConfig(CSB_Echo_Timer, TIM_IT_CC1, ENABLE);

	// 配置NVIC中断
	NVIC_InitStructure.NVIC_IRQChannel = TIM1_CC_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);

	// 使能TIM3
	TIM_Cmd(CSB_Echo_Timer, ENABLE);
}

/* 触发超声波测距 */
void CSB_Trigger(void)
{
	// 发送触发信号
	GPIO_ResetBits(CSB_Trigger_Port, CSB_Trigger_Pin);
	Delay_Us(5);  // 先拉低稳定5μs
	GPIO_SetBits(CSB_Trigger_Port, CSB_Trigger_Pin);
	Delay_Us(20);
	GPIO_ResetBits(CSB_Trigger_Port, CSB_Trigger_Pin);
}
